package com.car.action.api;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.car.action.util.CommonController;
import com.car.backend.opensource.AESDecode;
import com.car.common.model.Card;
import com.car.common.model.CardDiscuss;
import com.car.common.model.CardLike;
import com.car.common.model.ReportCards;
import com.car.common.model.ReportUsers;
import com.car.common.model.MessageUnreadNum;
import com.car.common.model.PropRecord;
import com.car.common.model.Sign;
import com.car.common.model.Sms;
import com.car.common.model.UserBlack;
import com.car.common.model.UserCheck;
import com.car.common.model.UserFans;
import com.car.common.model.UserSees;
import com.car.common.model.Users;
import com.car.common.model.UsersInfo;
import com.car.common.model.VipRecord;
import com.car.tx.UserService;
import com.dvzju.lotto.k3.Rand;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Db;
import com.utils.APIJSON;
import com.utils.DateUtil;
import com.utils.JwtToken;
import com.utils.PicUtil;
import com.utils.RongCloudUtil;
import com.utils.StringUtil;
import com.utils.SystemClock;
import com.utils.Toolkit;

public class UserController  extends CommonController  {

	public void pic_check_sex() {
		String message = check_user(false);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			String pic = getPara("pic");
			if (StringUtil.empty(pic)) {
				renderText(APIJSON.result(4001));
				return;
			}
			Map<String,Object> result = Maps.newHashMap();
			result.put("sex", 0);
			Long user_id = super.getUserId();	
			Users one = Users.dao.findById(user_id);
			if (!StringUtil.empty(one.getUserName())) {
				String[] user_name = one.getUserName().split(",");
				if (user_name .length > 4) {
					renderText(APIJSON.send(result));
					return;
				} else {
					String user_name_2 = one.getUserName() + "," + pic;
					Db.update("update users set user_name = '" + user_name_2 + "' where id = " + user_id);
				}
			} else {
				Db.update("update users set user_name = '" + pic +"' where id = " + user_id);
			}
			
			String body = "{\"type\":0,\"image_url\":\"" + PicUtil.QINIU_DIR + pic +"\"}";
			
			try {
				String json = AESDecode.sendPost2(body);
				JSONObject obj = JSONObject.parseObject(json);
				System.out.println(obj);
				int face_num  = obj.getIntValue("face_num");
				if (face_num > 0) {
					com.alibaba.fastjson.JSONArray gender = obj.getJSONArray("gender");
					result.put("sex", Integer.valueOf(String.valueOf(gender.get(0))) == 0 ? 2 :0);
					if (Integer.valueOf(String.valueOf(result.get("sex"))) == 2) {
						one.set("talk_end_time", SystemClock.now()/1000 + 3*365*24*3600L);
						one.set("vip_end_time", SystemClock.now()/1000 + 30*24*3600L);
						one.set("talk_badge", 3);
						one.set("auth_badge", 2);
						one.set("vip_badpe", 1);
						one.set("user_name", pic);
						one.update();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			renderText(APIJSON.send(result));
		}
		
		
	}
	
	/**
	 *  登录
	 * @param user_mobile
	 * @param user_password
	 * @param verify
	 */
	public void login() {
		String user_mobile = getPara("user_mobile");
		if (StringUtil.empty(user_mobile)) {
			renderText(APIJSON.result(1007));
			return;
		} 
		String user_password = getPara("user_password");
		if (StringUtil.empty(user_password)) {
			renderText(APIJSON.result(1005));
			return;
		} 
		Users users = Users.dao.findFirst("select id,status,nick_name,disable_time from users where user_mobile = '"+user_mobile+"' and user_password = '" + Users.password(getPara("user_password"))+"' order by id desc limit 1 ");
		if (users == null) {
			renderText(APIJSON.result(1001));
			return;
		} else {
			if (users.getStatus() == 1 ) {
				Long disableTime = users.getDisableTime();
				if (disableTime == null || disableTime < SystemClock.now()/1000L) {
					Map<String,Object> temp = Maps.newHashMap();
					temp.put("user_id", users.getId());
					String token = null;
					try {
						token = JwtToken.createToken(users.getId());
					} catch (Exception e) {
						e.printStackTrace();
					}
					temp.put("token", token);
					UsersInfo info = UsersInfo.dao.findFirst("select im_token from users_info where user_id = " + users.getId());
					if (info != null) {
						temp.put("im_token", info.get("im_token"));
					} else {
						Map<String, String> params = Maps.newHashMap();
						params.put("userId",   		String.valueOf(users.getId()));
						params.put("name",     		StringUtil.empty(users.getNickName())?"火星人": users.getNickName());
						if (StringUtil.empty(users.getUserHeader())) {
							params.put("portraitUri",     PicUtil.DEFAULT_HEAD);
						} else {
							params.put("portraitUri",     PicUtil.QINIU_DIR +  users.getUserHeader());
						}
						JSONObject jsonObject = RongCloudUtil.post("http://api-cn.ronghub.com/user/getToken.json", params);
						if (jsonObject.getIntValue("code") == 200) {
							String im_token = jsonObject.getString("token");
							Db.update("update users_info set im_token = '" + token + "' where user_id = " + users.getId()); 
							temp.put("im_token", im_token);
						}
					}
					temp.put("base_info", !StringUtil.empty(users.getNickName()));
					Long user_id = users.getId();
					List<Users> users_list = Users.dao.find("select id from users where is_true > 1 order by rand( ) limit  " + new Random().nextInt(3));
					for(Users u : users_list) {
						UserSees one1 = new UserSees();
	    				one1.setUserId(u.getId().intValue());
	    				one1.setTargetUserId(user_id.intValue());
	    				one1.setCreateTime(SystemClock.now()/1000L);
	    				one1.setUpdateTime(SystemClock.now()/1000L);
	    				if (one1.save()) {
	    					MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_SEE, user_id.intValue());
	    				}
					}
					renderText(APIJSON.send(0, temp, "登陆成功"));
				} else if (disableTime == -1L) {
					renderText(APIJSON.result(1002));
				} else if(disableTime > SystemClock.now()/1000L) {
					renderText(APIJSON.send(1002, null,"账号被禁用到" + DateUtil.commonDateTimeFormat.format(new Date(disableTime*1000L)) ));
				}
			}
		}
		
	}
	
	/**
	 * 自动登录
	 */
	public void oauth_login() {
		String openid = getPara("openid");
		if (StringUtil.empty(openid)) {
			renderText(APIJSON.result(4001));
			return;
		}
		// qq_openid wb_openid
		String type = getPara("type").trim();
		if (!("qq".equals(type) || "wx".equals(type) || "apple".equals(type))) {
			renderText(APIJSON.result(4001));
			return;
		} 
		if ("qq".equals(type)) {
			type = "qq_openid";
		}
		else if ("wx".equals(type)) {
			type = "wx_unionid";
		}
		else if ("apple".equals(type)) {
			type = "apple_id";
		}
		int user_id = 0;
		UsersInfo info = UsersInfo.dao.findFirst("select id,user_id,im_token from users_info where " + type +"='" +openid +"' order by id desc ");
		Users one = null;
		if (info == null) {
			// 首次登录
			one = new Users();
			one.setCreateTime(SystemClock.now()/1000L);
			one.setUpTime(SystemClock.now()/1000L);
			one.setUpdateTime(SystemClock.now()/1000L);
			one.set("device_id", getPara("device_id"));
			one.setStatus(1);
			if (one.save()) {
				user_id = one.getId().intValue();
				info = new UsersInfo();
				if ("qq".equals(type)) {
					type = "qq_openid";
					info.set("qq_openid", openid);
				}
				else if ("wx".equals(type)) {
					type = "wx_unionid";
					info.set("wx_unionid", openid);
				}else if ("apple".equals(type)) {
					type = "apple_id";
					info.set("apple_id", openid);
				}
				info.setUserId(user_id);
				info.save();
//				System.out.println("update users_info set " + type+" = '" + openid +"' where user_id =" + user_id );
				Db.update("update users_info set " + type+" = '" + openid +"' where user_id =" + user_id );
			}
		} else {
			user_id = info.getUserId();
		}
		one = Users.dao.findFirst("select id,status,nick_name,disable_time from users where id = " + user_id );
		if (one == null) {
			one = new Users();
			one.setCreateTime(SystemClock.now()/1000L);
			one.setUpTime(SystemClock.now()/1000L);
			one.setUpdateTime(SystemClock.now()/1000L);
			one.set("device_id", getPara("device_id"));
			one.setStatus(1);
			one.save();
		}
		if(one.getStatus() == 1 ) {
			Long disableTime = one.getDisableTime();
			if (disableTime == null || disableTime < SystemClock.now()/1000L) {
				Map<String,Object> temp = Maps.newHashMap();
				temp.put("user_id", one.getId());
				String token = null;
				try {
					token = JwtToken.createToken(one.getId());
				} catch (Exception e) {
					e.printStackTrace();
				}
				temp.put("token", token);
				if (info.get("im_token") != null) {
					temp.put("im_token", info.get("im_token"));
				} else {
					Map<String, String> params = Maps.newHashMap();
					params.put("userId",   		String.valueOf(user_id));
					params.put("name",     		"新人");
					if (StringUtil.empty(one.getUserHeader())) {
						params.put("portraitUri",     PicUtil.DEFAULT_HEAD);
					} else {
						params.put("portraitUri",     PicUtil.QINIU_DIR +  one.getUserHeader());
					}
					JSONObject jsonObject = RongCloudUtil.post("http://api-cn.ronghub.com/user/getToken.json", params);
					if (jsonObject.getIntValue("code") == 200) {
						String im_token = jsonObject.getString("token");
						Db.update("update users_info set im_token = '" + im_token + "' where user_id = " + user_id); 
						temp.put("im_token", im_token);
					}
				}
				temp.put("base_info", !StringUtil.empty(one.getNickName()));
				renderText(APIJSON.send(0, temp, "登陆成功"));
			} else if (disableTime == -1L) {
				renderText(APIJSON.result(1002));
			} else if(disableTime > SystemClock.now()/1000L) {
				renderText(APIJSON.send(1002, null,"账号被禁用到" + DateUtil.commonDateTimeFormat.format(new Date(disableTime*1000L)) ));
			}
		}
		

	}
	
	
	/**
	 *  注册
	 * @param user_mobile
	 * @param user_password
	 * @param verify
	 */
	public void register() {
		String user_mobile = getPara("user_mobile");
		if (StringUtil.empty(user_mobile)) {
			renderText(APIJSON.result(1007));
			return;
		} 
		String user_password = getPara("user_password");
		if (StringUtil.empty(user_password)) {
			renderText(APIJSON.result(1005));
			return;
		} 
		String verify = getPara("verify");
		if (StringUtil.empty(verify)) {
			renderText(APIJSON.result(1013));
			return;
		}
		Users exist = Users.dao.findFirst("select id from users where user_mobile = '" + user_mobile +"' order by id desc limit 1 ");
		if(exist != null) {
			renderText(APIJSON.result(1009));
			return;
		}
		
		Sms existSms = Sms.dao.findFirst("select id from sms where mobile = '" + user_mobile +"' and type ='register' and code = '" + verify +"' order by id desc limit 1 ");
		if (existSms == null) {
			renderText(APIJSON.result(1014));
			return;
		} 
		Users one = new Users();
		one.set("user_mobile", getPara("user_mobile"));
		one.set("user_password", Users.password(getPara("user_password")));
		one.set("create_time", SystemClock.now()/1000L);
		one.set("device_id", getPara("device_id"));
		one.save();
		
		
		String token = null;
		try {
			token = JwtToken.createToken(one.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		String agent= getRequest().getHeader("user-agent");
		if(agent.contains("iPhone")||agent.contains("iPod")||agent.contains("iPad")){
			renderText(APIJSON.send(0,token,"注册成功"));
		} else {
			Long user_id = one.getId();
			Map<String,Object> temp = Maps.newHashMap();
			temp.put("user_id", user_id);
			temp.put("token",   token);
			UsersInfo info = new UsersInfo();
			info.setUserId(user_id.intValue());
			Map<String, String> params = Maps.newHashMap();
			params.put("userId",   		String.valueOf(user_id));
			params.put("name",     		StringUtil.empty(one.getNickName())?"火星人": one.getNickName());
			if (StringUtil.empty(one.getUserHeader())) {
				params.put("portraitUri",     PicUtil.DEFAULT_HEAD);
			} else {
				params.put("portraitUri",     PicUtil.QINIU_DIR +  one.getUserHeader());
			}
			JSONObject jsonObject = RongCloudUtil.post("http://api-cn.ronghub.com/user/getToken.json", params);
			if (jsonObject.getIntValue("code") == 200) {
				String im_token = jsonObject.getString("token");
				Db.update("update users_info set im_token = '" + token + "' where user_id = " + user_id); 
				temp.put("im_token", im_token);
				info.setImToken(im_token);
			}
			temp.put("base_info", !StringUtil.empty(one.getNickName()));
			info.save();
			renderText(APIJSON.send(0, temp, "登陆成功"));
		}
		
	}
	
	/**
     * 获取用户基本信息
     */
	public void get_user_info() {
		String user_id = null;
		if(StringUtil.empty(getPara("user_id"))) {
			user_id = String.valueOf(super.getUserId());
		} else {
			user_id = getPara("user_id");
		}
		
		String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
		sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit  from users as u left join area ae on ae.code = u.area_id where u.id = " + user_id;
		
		Users users = Users.dao.findFirst(sql);
		Map<String,Object> temp = Maps.newHashMap();
		temp.put("user_info", Users.dao.info(users,null));
		renderText(APIJSON.send(temp));
	}
	
	
	public void sex() {
		Map<String,Object> temp = Maps.newLinkedHashMap();
		temp.put("1", "男");
		temp.put("2", "女");
		temp.put("3", "CD");
		temp.put("4", "FtM");
		temp.put("5", "MtF");
		renderText(APIJSON.send(temp));
	}
	
	/**
	 * 我的动态
	 */
	public void my_card() {
	   Long user_id = super.getUserId();
	   int page = 1;
       if(!StringUtil.empty(getPara("page"))) {
    	   page = getParaToInt("page");
       }
       if (!StringUtil.empty(getPara("user_id"))) {
    	   user_id = getParaToLong("user_id");
       }
       renderText(APIJSON.send(Card.dao.my(user_id, page)));
	}
	
	/**
	 * 我收藏的动态
	 */
	public void my_collect_card() {
	   Long user_id = super.getUserId();
	   int page = 1;
       if(!StringUtil.empty(getPara("page"))) {
    	   page = getParaToInt("page");
       }
       if (!StringUtil.empty(getPara("user_id"))) {
    	   user_id = getParaToLong("user_id");
       }
       renderText(APIJSON.send(Card.dao.my_collect(user_id, page)));
	}
	
	/**
	 * 我的动态(评论)
     * 只展示文字内容跟用户头像昵称时间
	 */
	public void my_discuss() {
	   Long user_id = super.getUserId();
	   int page = 1;
       if(!StringUtil.empty(getPara("page"))) {
    	   page = getParaToInt("page");
       }
       if (!StringUtil.empty(getPara("user_id"))) {
    	   user_id = getParaToLong("user_id");
       }
       renderText(APIJSON.send(CardDiscuss.dao.sel_my_list(user_id.intValue(), page)));
	}
	
	 /**
     * 点赞的动态(点赞)
     */
    public void my_like_card(){
 	   Long user_id = super.getUserId();
 	   int page = 1;
       if(!StringUtil.empty(getPara("page"))) {
     	  page = getParaToInt("page");
       }
       if(!StringUtil.empty(getPara("user_id"))) {
     	  user_id = getParaToLong("user_id");
       }
       renderText(APIJSON.send(CardLike.dao.sel_my_list(user_id.intValue(), page)));
 	}
	
    /**
     * 获取浏览过我的用户信息
     * @param page 1
     * @param token eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTAyMTg4MzUsImF1ZCI6IkFQUCIsImlzcyI6IlNlcnZpY2UiLCJ1c2VyX2lkIjoiMTUwIiwiaWF0IjoxNTU4NjgyODM1fQ.Ma-LRYnjLAx5NayOITyKxn_6s6042FlYX_rRx7l60c8
     */
	public void see_me() {
		String message = check_user(false);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			int page = 1;
	        if(!StringUtil.empty(getPara("page"))) {
	        	page = getParaToInt("page");
	        }
			Long user_id = super.getUserId();
			MessageUnreadNum.dao.clearNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_SEE, user_id.intValue());
			List<UserSees> useridList = UserSees.dao.find("select user_id from user_sees where target_user_id = " + user_id +" order by update_time desc limit " + (page -1 )*15 + ", 15 ");
			ArrayList<Map<String,Object>> result = Lists.newArrayList();
			for(UserSees one : useridList) {
				String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
				sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit  from users as u left join area ae on ae.code = u.area_id where u.id = " + one.getUserId();
				
				Users user = Users.dao.findFirst(sql);
				Map<String,Object> temp = Users.dao.info(user,null);
				UserFans fans =	UserFans.dao.findFirst("select id from user_fans where  user_id = " + one.getUserId() + " and target_user_id ="+ user_id +" order by id desc limit 1 ");
				int follow = 1;
				if (fans != null) {
					follow = 2;
				}
				temp.put("follow", follow);
				result.add(temp);
			}
			renderText(APIJSON.send(result));
		}
	}
	
	
	/**
	  * 设置隐身  1 出现 2 隐身
	  */
	public void set_nearby(){
	   	String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			Db.update("update users set is_show_nearby = " + getPara("value") + " where id = " + user_id );
			renderText(APIJSON.result(0));
		}
	}
	/**
    * 举报人
    */
	public void user_report(){
	   	String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			int target_user_id = getParaToInt("user_id");
			ReportUsers one = ReportUsers.dao.findFirst("select * from report_users where status =1 and report_user_id = "+ getPara("user_id") );
			if (one == null) {
				Long user_id = super.getUserId();
				one = new ReportUsers();
				one.setReportUserId(target_user_id);
				one.setUserId(user_id.intValue());
				one.setStatus(1);
				one.save();
			}
			renderText(APIJSON.send(0,null ,"举报成功，客服会24小时之内做出对应处理!"));
		}
	}
	   
	   
    /**
     * 拉入黑名单/取消拉入黑名单
     * @param  black_user_id
     */
	 public void user_black() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
	        Long user_id = super.getUserId();
	        UserBlack one = UserBlack.dao.findFirst("select id,status,user_id,black_user_id from user_black where user_id = " + user_id + " and black_user_id = " + getPara("black_user_id"));
	        if (one == null) {
	        	one = new UserBlack();
	        	one.set("user_id", user_id);
	        	one.set("black_user_id", getPara("black_user_id"));
	        	one.set("status", 1);
	        	one.set("create_time", SystemClock.now()/1000L);
	        	if (one.save()) {
	        		Map<String,String> params = Maps.newHashMap();
		        	params.put("userId", String.valueOf(user_id));
		        	params.put("blackUserId", getPara("black_user_id"));
		        	RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/add.json", params);
	        	}
	        } else {
	        	if (one.getStatus() == 1) {
	        		Db.update("update user_black set status = 2 where id = " + one.getId());
	        		Map<String,String> params = Maps.newHashMap();
		        	params.put("userId", String.valueOf(user_id));
		        	params.put("blackUserId", getPara("black_user_id"));
		        	RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/remove.json", params);
	        	} else {
	        		Db.update("update user_black set status = 1 where id = " + one.getId());
	        		Map<String,String> params = Maps.newHashMap();
		        	params.put("userId", String.valueOf(user_id));
		        	params.put("blackUserId", getPara("black_user_id"));
		        	RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/add.json", params);
	        	}
	        }
	        
	        renderText(APIJSON.result(0));
		}
	 }
	
	
	/**
     * 我的黑名单
     */
	public void my_black_list() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			int page = 1;
	        if(!StringUtil.empty(getPara("page"))) {
	        	page = getParaToInt("page");
	        }
	        Long user_id = super.getUserId();
	        List<Map<String,Object>> result = UserBlack.dao.sel_list(user_id.intValue(),page);
	        renderText(APIJSON.send(result));
		}
		
	}

    /**
     * 我的主页--一个帖子  TODO 不要
     */
    public void sel_my_card() {
    	renderText(APIJSON.result(0));
    }
    
	
	/**
	 * 我的主页评论  TODO 未定
	 */
	public void sel_my_discuss() {
		renderText(APIJSON.result(0));
	}
	
	/**
	 * 忘记密码
	 */
	public void repassword() {
		renderText(APIJSON.result(0));
	}
	
	/**
	 * 签到列表
	 */
	public void sign_list() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			Calendar cal = Calendar.getInstance();
			cal.setTimeInMillis(SystemClock.now());
			cal.set(Calendar.DATE, cal.get(Calendar.DATE) -1); 
			System.out.println(DateUtil.commonDateFormat.format(cal.getTime()));
			Sign one = Sign.dao.findFirst("select `index`,real_day from sign where user_id = " + user_id +" and  `index` != 7  and createtime > " + cal.getTimeInMillis()/1000L +  " order by id desc limit 1");
			if (one == null) {
				one = new Sign();
				one.setIndex(0);
				one.setRealDay(DateUtil.commonDateFormat.format(cal.getTime()));
			}
			renderText(APIJSON.send(one));
		}
		
	}
	
	/**
	 * 签到
	 */
	public void sign() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			Map<String,Object> result = UserService.one.sign(user_id);
			if (result != null) {
				renderText(APIJSON.send(result));
			} else {
				renderText(APIJSON.result(0));
			}
			
		}
	}
	
	/**
	 * 认证1 手机认证
	 */
	public void mobile_check() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			Users users = Users.dao.findById(user_id);
			if (!StringUtil.empty(users.getUserMobile())) {
				Db.update("update users set auth_badge = 1 where auth_badge = 0 and id = " + user_id);
			} else { 
				String user_mobile = getPara("user_mobile");
				String verify = getPara("verify");
				if (StringUtil.empty(verify)) {
					renderText(APIJSON.result(1013));
					return;
				}
				Users exist = Users.dao.findFirst("select id from users where user_mobile = '" + user_mobile +"' order by id desc limit 1 ");
				if(exist != null) {
					renderText(APIJSON.result(1009));
					return;
				}
				
				Sms existSms = Sms.dao.findFirst("select id from sms where mobile = '" + user_mobile +"' and type ='auth' and code = '" + verify +"' order by id desc limit 1 ");
				if (existSms == null) {
					renderText(APIJSON.result(1014));
					return;
				} 
				Db.update("update users set auth_badge = 1,user_mobile = '"+ user_mobile +"' where id = " + user_id);
			}
			renderText(APIJSON.result(0));
		}
	}
	
	/**
	 * 认证2 性别认证
	 */
	public void sex_check() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			Users users = Users.dao.findById(user_id);
			if (!StringUtil.empty(users.getUserMobile())) {
				UserCheck check = UserCheck.dao.findById(user_id);
				if (check == null) {
					check = new UserCheck();
					check.set("user_id", user_id);
					check.set("head", getPara("img"));
					check.set("status", 2);
					check.save();
				}
			}
			renderText(APIJSON.result(0));
		}
	}
	
	/**
	 * 认证3 身份证认证
	 */
	public void id_check() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			Users users = Users.dao.findById(user_id);
			if (!StringUtil.empty(users.getUserMobile())) {
				UserCheck check = UserCheck.dao.findById(user_id);
				if (check == null) {
					
					int result = com.car.backend.opensource.HttpUtils.check_name(getPara("name"), getPara("card"));
					if (result == 0) {
						check = new UserCheck();
						check.set("user_id", user_id);
						check.set("real_name", getPara("name"));
						check.set("IDcard", getPara("card"));
						check.set("status", 3);
						check.save();
					} else {
						renderText(APIJSON.result(6011));
						return;
					}
					
				} else {
					int result = com.car.backend.opensource.HttpUtils.check_name(getPara("name"), getPara("card"));
					if (result == 0) {
						Db.update("update user_check set status = 3 ,real_name = '" + getPara("name") +"' ,IDcard = '" + getPara("card") + "'  where  user_id = " + user_id);
					} else {
						renderText(APIJSON.result(6011));
						return;
					}
					
				}
				int result = com.car.backend.opensource.HttpUtils.check_name(getPara("name"), getPara("card"));
				if (result == 0) {
					Db.update("update users set auth_badge = 3 where  id = " + user_id);
				} else {
					renderText(APIJSON.result(6011));
					return;
				}
			}
			renderText(APIJSON.result(0));
		}
	}
	
	
	/*
	 * 检查认证状态
	 */
	public void status_check() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			Users users = Users.dao.findById(user_id);
			int auth_badge = users.getInt("auth_badge");
			if (auth_badge == 0) {
				if (!StringUtil.empty(users.getUserMobile())) {
					Db.update("update users set auth_badge = 1 where auth_badge = 0 and id = " + user_id);
					auth_badge = 1;
				} 
			} else if(auth_badge == 1) {
				UserCheck one = UserCheck.dao.findById(user_id);
				if (one != null) {
					if (!StringUtil.empty(one.getStr("head"))) {
						auth_badge = 4;
					}
				} 
			} else if(auth_badge == 2) {
				
			}
			
			Map<String,Object> result = Maps.newHashMap();
			result.put("status", auth_badge);
			renderText(APIJSON.send(result));
		}
	}
	
	
	/**
	 * 重置密码
	 */
	public void reset() {
		String user_mobile = getPara("user_mobile");
		String verify = getPara("verify");
		if (StringUtil.empty(user_mobile)) {
			renderText(APIJSON.result(4001));
			return;
		}
		if (StringUtil.empty(verify)) {
			renderText(APIJSON.result(1013));
			return;
		}
		Sms existSms = Sms.dao.findFirst("select id from sms where mobile = '" + user_mobile +"' and type ='repassword' and code = '" + verify +"' order by id desc limit 1 ");
		if (existSms == null) {
			renderText(APIJSON.result(1014));
			return;
		} 
		Db.update("update users set user_password = '" + Users.password(getPara("user_password")) +"' where user_mobile = '" + user_mobile +"'");
		renderText(APIJSON.result(0));
	}
	
	public void mobile_wrap() {
		Long user_id = super.getUserId();
		String user_mobile = getPara("user_mobile");
		String verify = getPara("verify");
		if (StringUtil.empty(user_mobile)) {
			renderText(APIJSON.result(4001));
			return;
		}
		if (StringUtil.empty(verify)) {
			renderText(APIJSON.result(1013));
			return;
		}
		Sms existSms = Sms.dao.findFirst("select id from sms where mobile = '" + user_mobile +"' and type ='auth' and code = '" + verify +"' order by id desc limit 1 ");
		if (existSms == null) {
			renderText(APIJSON.result(1014));
			return;
		} else{
			Db.update("update users set user_mobile ='"+user_mobile+"'  where id = "+user_id);
		}
		renderText(APIJSON.result(0));
	}
	
	public void apply_out() {
		if (StringUtil.empty(getPara("account"))) {
			renderText(APIJSON.result(1037));
			return;
		}
		if (StringUtil.empty(getPara("money"))) {
			renderText(APIJSON.result(1036));
			return;
		}
		String account = getPara("account");
		int money = getParaToInt("money");
		if (money < 300) {
			renderText(APIJSON.result(1047));
			return;
		}
		Long user_id = super.getUserId();
		Users users = Users.dao.findById(user_id);
		if (users.getInt("auth_badge") != 3 ) {
			renderText(APIJSON.result(6002));
			return;
		}
		
		int free_hot = users.getInt("free_hot");
		if (money * 100 > free_hot) {
			renderText(APIJSON.result(1044));
			return;
		} else {
			VipRecord one = new VipRecord();
			one.setUserId(user_id.intValue());
			one.setOrderNum(Toolkit.newTradeNo());
			one.setTitle("热度提现账号:"+ account + " 金额:" + money +" RMB ");
			one.setBuyType("User");
			one.setHot(money * 100 );
			one.setStatus(3);
			one.setOrderType(2);
			one.setCreateTime(SystemClock.now()/1000L);
			one.setUpdateTime(SystemClock.now()/1000L);
			if (user_id == 140901L) {
				one.setPrice(new BigDecimal(0.01));
			}
			one.save();
			Db.update("update users set free_hot = free_hot - " + money * 100 +"  where id = " + user_id);
			renderText(APIJSON.result(0));
			return;
		}
	}
	
	
	/**
	 * 我的土豪榜(发出的礼物)
	 */
	public void consume_list() {
		String message = check_user(true);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			if (!StringUtil.empty(getPara("user_id"))) {
				user_id = getParaToLong("user_id");
			}
			List<PropRecord> recordList = PropRecord.dao.find("SELECT sum(hot_val) AS hot_val, target_user_id FROM prop_record WHERE user_id =" + user_id +" GROUP BY target_user_id HAVING hot_val > 0 ORDER BY hot_val DESC");
			List<Map<String,Object>> result = Lists.newArrayList();
			for(PropRecord one: recordList) {
				String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
				sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit  from users as u left join area ae on ae.code = u.area_id where u.id = " + one.get("target_user_id");
				Users user1 = Users.dao.findFirst(sql);
				Map<String,Object> user_info = Users.dao.info(user1,null);
				user_info.put("hot_val", one.get("hot_val"));
				result.add(user_info);
			}
			renderText(APIJSON.send(result));
		}	
		
	}
	
	/**
	 * 我的魅力榜(收到的礼物)
	 */
	public void charm_list() {
		String message = check_user(false);
		if (!StringUtil.empty(message)) {
			renderText(message);
		} else {
			Long user_id = super.getUserId();
			if (!StringUtil.empty(getPara("user_id"))) {
				user_id = getParaToLong("user_id");
			}
			List<PropRecord> recordList = PropRecord.dao.find("SELECT sum(hot_val) AS hot_val, user_id FROM prop_record WHERE target_user_id =" + user_id +" GROUP BY user_id HAVING hot_val > 0 ORDER BY hot_val DESC");
			List<Map<String,Object>> result = Lists.newArrayList();
			for(PropRecord one: recordList) {
				String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
				sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit  from users as u left join area ae on ae.code = u.area_id where u.id = " + one.get("user_id");
				Users user1 = Users.dao.findFirst(sql);
				Map<String,Object> user_info = Users.dao.info(user1,null);
				user_info.put("hot_val", one.get("hot_val"));
				result.add(user_info);
			}
			renderText(APIJSON.send(result));
		}	
	}
	
    /**
     * 更新用户状态(融云在线状态订阅接口)
     * [{"userid":"2","status":"1","os":"","time":"1516247451977"},{"userid":"2","status":"0","os":"Websocket","time":"1516247452739"},{"userid":"2","status":"1","os":"","time":"1516247452948"}]
     *{"timestamp":"1516255151087","nonce":"1860733168","signature":"4ddf8bee64c89bf564f577afd42f0de165352fca","appKey":"lmxuhwagl0gbd"}
     */
	public void update_status() {
		String json = HttpKit.readData(getRequest());
		System.out.println("IM update_status:"+json);
		JSONArray array = JSONArray.parseArray(json);
		if (array != null) {
			for(int i = 0 ; i < array.size() ; i++) {
				//IM update_status:[{"userid":"1000587","status":"0","os":"iOS","time":1567739582563}]
				Db.update("update users set login_status = " + array.getJSONObject(i).get("status")+", logout_time = " + array.getJSONObject(i).getLongValue("time") /1000L +" where id = " + array.getJSONObject(i).get("userid"));
			}
		}
		renderText(APIJSON.result(0));
	}
	
}
